package br.com.winesys.geta.persistence.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

public final class JDBCConnectionFactoryBuilder {

	private static Map<String, JDBCConnectionFactory> factories = new TreeMap<String, JDBCConnectionFactory>();
	private static boolean sharedConnection = false;

	private JDBCConnectionFactoryBuilder() {
		throw new AssertionError("JDBCConnectionFactoryBuilder has only static methods");
	}

	public static void setSharedConnection(boolean sharedConnection) {
		if (factories.isEmpty()) {
			JDBCConnectionFactoryBuilder.sharedConnection = sharedConnection;
		} else {
			throw new RuntimeException("Can not set sharedConnection after creating a connection");
		}
	}

	public static JDBCConnectionFactory getConnectionFactory(String connectionName) throws IOException {
		JDBCConnectionFactory connectionFactory = factories.get(connectionName);
		if (connectionFactory == null) {
			String configDataName = String.format("/%s.properties", connectionName);
			InputStream configData = JDBCConnectionFactoryBuilder.class.getResourceAsStream(configDataName);
			Properties properties = new Properties();
			properties.load(configData);
			connectionFactory = new JDBCConnectionFactory(properties, sharedConnection);
			factories.put(connectionName, connectionFactory);
		}
		return connectionFactory;
	}
}
